package com.fart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fart.common.BusinessException;
import com.fart.domain.Category;
import com.fart.domain.Dish;
import com.fart.domain.Setmeal;
import com.fart.mapper.CategoryMapper;
import com.fart.service.CategoryService;
import com.fart.service.DishService;
import com.fart.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl
        extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;


    //自定义根据id删除分类
    @Override
    public void remove(Long id) {
        //1.根据当前分类的ID，查询该分类下是否存在菜品，如果存在，则提示错误信息
        //1.1 查询的相关表: Dish 添加查询条件 -> 创建条件构造器
        LambdaQueryWrapper<Dish> dishLqw = new LambdaQueryWrapper<>();
        // id = 1397844263642378242 -> 使用等值查询
        dishLqw.eq(Dish::getCategoryId,id);
        /*sql: select * from dish where id = 1397844263642378242
          sql: select count() from dish where id = 1397844263642378242
         */
        //调用查询总记录数的方法
        int count = dishService.count(dishLqw);
        //判断查询结果是否 > 0
        if (count > 0){
            //则抛出异常 -> 自定义异常
            throw new BusinessException("当前菜品存在,不能删除");
        }

        //2.根据当前分类的ID，查询该分类下是否存在套餐，如果存在，则提示错误信息
        LambdaQueryWrapper<Setmeal> setmealLqw = new LambdaQueryWrapper<>();
        setmealLqw.eq(Setmeal::getCategoryId,id);
        int count1 = setmealService.count(setmealLqw);
        if (count1 > 0){
            //则抛出异常 -> 自定义异常
            throw new BusinessException("当前套餐存在,不能删删除");
        }

        //3.执行正常的删除分类操作
        removeById(id);
    }
}
